package com.executor.gateway.controller;

import com.executor.gateway.model.po.ApiConfig;
import com.executor.gateway.model.po.GatewayConfig;
import com.executor.gateway.service.DynamicRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置管理控制器
 * 提供动态路由和API配置管理的REST API
 * 
 * @author miaoguoxin
 * @date 2024/01/01
 */
@RestController
@RequestMapping("/config")
@Slf4j
public class ConfigurationController {

    @Autowired
    private DynamicRouteService dynamicRouteService;

    /**
     * 刷新所有路由配置
     */
    @PostMapping("/routes/refresh")
    public ResponseEntity<Map<String, Object>> refreshAllRoutes() {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer result = dynamicRouteService.refreshAllRoute();
            response.put("success", result == 1);
            response.put("message", result == 1 ? "路由配置刷新成功" : "路由配置刷新失败");
            response.put("timestamp", LocalDateTime.now().toString());
            
            log.info("All routes refreshed, result: {}", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error refreshing all routes", e);
            response.put("success", false);
            response.put("message", "路由配置刷新失败: " + e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 更新单个路由配置
     */
    @PutMapping("/routes/{serviceId}")
    public ResponseEntity<Map<String, Object>> updateRoute(
            @PathVariable String serviceId, 
            @RequestBody GatewayConfig gatewayConfig) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 设置serviceId
            gatewayConfig.setServiceId(serviceId);
            
            Integer result = dynamicRouteService.updateRoute(gatewayConfig);
            response.put("success", result == 1);
            response.put("message", result == 1 ? "路由更新成功" : "路由更新失败");
            response.put("serviceId", serviceId);
            response.put("timestamp", LocalDateTime.now().toString());
            
            log.info("Route updated for service: {}, result: {}", serviceId, result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error updating route for service: " + serviceId, e);
            response.put("success", false);
            response.put("message", "路由更新失败: " + e.getMessage());
            response.put("serviceId", serviceId);
            response.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 删除路由配置
     */
    @DeleteMapping("/routes/{serviceId}")
    public ResponseEntity<Map<String, Object>> deleteRoute(@PathVariable String serviceId) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer result = dynamicRouteService.deleteRoute(serviceId);
            response.put("success", result == 1);
            response.put("message", result == 1 ? "路由删除成功" : "路由删除失败");
            response.put("serviceId", serviceId);
            response.put("timestamp", LocalDateTime.now().toString());
            
            log.info("Route deleted for service: {}, result: {}", serviceId, result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error deleting route for service: " + serviceId, e);
            response.put("success", false);
            response.put("message", "路由删除失败: " + e.getMessage());
            response.put("serviceId", serviceId);
            response.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 刷新API配置
     */
    @PostMapping("/apis/refresh")
    public ResponseEntity<Map<String, Object>> refreshApiConfigs() {
        Map<String, Object> response = new HashMap<>();
        try {
            dynamicRouteService.refreshApi();
            response.put("success", true);
            response.put("message", "API配置刷新成功");
            response.put("timestamp", LocalDateTime.now().toString());
            
            log.info("API configurations refreshed successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error refreshing API configurations", e);
            response.put("success", false);
            response.put("message", "API配置刷新失败: " + e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 刷新IP黑白名单
     */
    @PostMapping("/ips/refresh")
    public ResponseEntity<Map<String, Object>> refreshIpLists() {
        Map<String, Object> response = new HashMap<>();
        try {
            dynamicRouteService.refreshIpList();
            response.put("success", true);
            response.put("message", "IP黑白名单刷新成功");
            response.put("timestamp", LocalDateTime.now().toString());
            
            log.info("IP lists refreshed successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error refreshing IP lists", e);
            response.put("success", false);
            response.put("message", "IP黑白名单刷新失败: " + e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 重新加载所有配置
     */
    @PostMapping("/reload")
    public ResponseEntity<Map<String, Object>> reloadAllConfigurations() {
        Map<String, Object> response = new HashMap<>();
        try {
            dynamicRouteService.loadRoutes();
            response.put("success", true);
            response.put("message", "所有配置重新加载成功");
            response.put("timestamp", LocalDateTime.now().toString());
            
            log.info("All configurations reloaded successfully");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error reloading all configurations", e);
            response.put("success", false);
            response.put("message", "配置重新加载失败: " + e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取网关配置状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getConfigurationStatus() {
        Map<String, Object> response = new HashMap<>();
        try {
            response.put("status", "active");
            response.put("timestamp", LocalDateTime.now().toString());
            response.put("message", "配置管理服务正常运行");
            
            // 可以添加更多状态信息
            Map<String, Object> details = new HashMap<>();
            details.put("routesLoaded", true);
            details.put("apisLoaded", true);
            details.put("ipListsLoaded", true);
            response.put("details", details);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Error getting configuration status", e);
            response.put("status", "error");
            response.put("message", "获取配置状态失败: " + e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.badRequest().body(response);
        }
    }
}